#include "Directory.h"
using namespace std;

Directory::Directory(const string& path)
{
    _dir = NULL;
    _path = path;
}



Directory::Directory(Directory& other)
{
    _path = other._path;
    _dir = opendir(_path.c_str());

    if(_dir != NULL)
        seekdir(_dir, telldir(other._dir));
}



Directory::~Directory()
{
    if(_dir != NULL)
        closedir(_dir);
}



string Directory::getPath()
{
    return _path;
}



bool Directory::open()
{
    _dir = opendir(_path.c_str());

    if(_dir != NULL)
        return true;
    else
        return false;
}



void Directory::close()
{
    if(_dir != NULL)
    {
        closedir(_dir);
        _dir = NULL;
    }
}


bool Directory::nextFilename(string& filename)
{
    if(_dir != NULL)
    {
        do
        {
            struct dirent* entry = readdir(_dir);

            // Si il n'y a plus rien à lire
            if(entry == NULL)
                return false;

            filename = entry->d_name;
        }
        while(filename == "." || filename == "..");

        return true;
    }

    return false;
}



void Directory::rewind()
{
    if(_dir != NULL)
        rewinddir(_dir);
}



Directory& Directory::operator=(const Directory& other)
{
    if(_dir != NULL)
        closedir(_dir);

    _path = other._path;
    _dir = opendir(_path.c_str());

    if(_dir != NULL)
        seekdir(_dir, telldir(other._dir));

    return *this;
}



void Directory::create(string dir)
{
#ifdef _WIN32
    int l=dir.length();
    for(int i=0 ; i<l ; ++i)
    {
        if(dir[i]=='/')
        {
            dir[i]='\\';
        }
    }
    string command("mkdir " + dir);
#else
    string command("mkdir '" + dir + "'");
#endif

    system(command.c_str());
}



string Directory::getDirFile(string file)
{
    if(file == "" || file == "/")
        return file;

    if(file[file.size()-1] == '/' || file[file.size()-1] == '\\')
        return file.substr(0, file.size()-1);

    int pos1 = file.rfind('/');
    int pos2 = file.rfind('\\');
    unsigned int max;

    if(pos1 > pos2)
        max = pos1;
    else
        max = pos2;

    if(max == string::npos)
        return ".";

    return file.substr(0, max);
}




